import type { UseFetchOptions } from "#app";
import type { ApiResult } from "~~/global";

/**
 * 通用请求
 * @param url 请求地址
 * @param opts 配置项
 */
export default async function useRequest<ResT = unknown>(url: string, opts?: UseFetchOptions<ApiResult<ResT>>) {
    const config = useRuntimeConfig();
    const { data } = await useFetch<ApiResult<ResT>>(url, {
        baseURL: config.public.serverApi.host,
        onRequest({ request, options }) {
            const { accessToken } = useUserStore();
            options.headers = {
                'Authorization': `Bearer ${accessToken}`
            }
            if (process.server) console.log('地址:', request.toString(), '请求头-->', options.headers);
        },
        onRequestError({ error, options, request }) {
            throw createError(`${request.toString()} 请求失败,请检查网络`)
        },
        ...opts
    })
    if (!data.value) {
        throw createError({ statusCode: 500, message: '请求成功但返回数据错误' })
    }
    return data.value as ApiResult<ResT>
}